package com.hhck.controller;

import com.hhck.constants.Constants;
import com.hhck.entity.CurrentUser;
import com.hhck.entity.OutStore;
import com.hhck.entity.Page;
import com.hhck.entity.Result;
import com.hhck.service.OutStoreService;
import com.hhck.service.StoreService;
import com.hhck.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/outstore")
public class OutStoreController {

    @Autowired
    private OutStoreService outStoreService;

    @Autowired
    private TokenUtils tokenUtils;

    @Autowired
    private StoreService storeService;

    /**
     * 添加出库单（商品出库）
     */
    @PostMapping("/outstore-add")
    public Result outStoreAdd(@RequestBody OutStore outStore, @RequestHeader(Constants.HEADER_TOKEN_NAME) String token) {

        // 获取当前登录用户（出库单创建者）
        CurrentUser currentUser = tokenUtils.getCurrentUser(token);
        // 设置出库单创建者
        outStore.setCreateBy(currentUser.getUserId());
        // 出库价格和先和售价保持一致
        outStore.setOutPrice(outStore.getSalePrice());

        return outStoreService.saveOutStore(outStore);
    }

    /**
     * 查询所有仓库
     */
    @GetMapping("/store-list")
    public Result storeList() {
        return Result.ok(storeService.queryAllStore());
    }

    /**
     * 分页查询出库单列表（条件查询）
     */
    @GetMapping("/outstore-page-list")
    public Result outstorePageList(Page page, OutStore outStore) {
        return Result.ok(outStoreService.queryOutStoreByPage(page, outStore));
    }

    /**
     * 确认出库
     */
    @PutMapping("/outstore-confirm")
    public Result outstoreConfirm(@RequestBody OutStore outStore) {

        try {
            int num = outStoreService.modifyOutStoreIsOutByoutsId(outStore);
            if (num == -1) {
                return Result.err(Result.CODE_ERR_BUSINESS, "商品库存不足！");
            } else if (num == 2) {
                return Result.ok("出库成功！");
            } else {
                return Result.err(Result.CODE_ERR_BUSINESS, "出库失败！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.err(Result.CODE_ERR_BUSINESS, "出库失败！");
        }
    }

}

